<?php
/**
 * @version $Id: atransaction.php 72 2011-10-24 09:50:50Z lnmtrung $
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
jimport('joomla.application.component.model');  

class WrdModelExchange extends WrdModel 
{
    var $_data;
	var $_id;
	var $_total = null;
	var $_pagination = null;
	var $_limit = null;
	var $_limitstart = null;

	function __construct(){
		parent::__construct();
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		
		$this->_limit = $mainframe->getUserStateFromRequest( $context.$view.'limit', 'limit', $mainframe->getCfg('list_limit'), 0);
        $this->_limitstart = $mainframe->getUserStateFromRequest( $context.$view.'limitstart', 'limitstart', 0 );

		$this->setState('limit', $this->_limit);
		$this->setState('limitstart', $this->_limitstart);
	}

	function getData(){
		if (empty($this->_data)){
			$query = $this->_buildQuery();
			$this->_db->setQuery( $query, $this->_limitstart, $this->_limit );
			$this->_data = $this->_db->loadObjectList();
		}
		return $this->_data;
	}

	function getTotal(){
		if (empty($this->_total)){
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}
		return $this->_total;
	}

	function getPagination(){
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->_limitstart, $this->_limit );
		}
		return $this->_pagination;
	}

	function _buildQuery(){
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');

		$orderby 			= $this->_buildContentOrderBy();
		$search 			= $mainframe->getUserStateFromRequest( $context.$view.'search','search','','string');
		
		$search 			= JString::strtolower( $search );
		$where = array();

		if ( $search ){
            $where[] = 'pro.member_id = '.intval($search);
		}
		
		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );
		$query = ' SELECT 
					e.id,
					u.name as user_name  ,
					e.user_id,
					e.transaction ,
					e.type ,
					e.point ,
					e.expire ,
					e.point ,
					e.des,
					cre.name as created_user, 
					e.created_date,
					mo.name as modify_user,
					e.modify_date, 
					pro.member_id as member_id,
					tr.date_receipt as date_receipt
                     
                	FROM #__wrd_point as e
                	LEFT JOIN #__users as u ON u.id = e.user_id
                	LEFT JOIN #__users as cre ON cre.id = e.created_id
                	LEFT JOIN #__users as mo ON mo.id = e.modify_id
                	LEFT JOIN #__wrd_profile pro ON pro.user_id = e.user_id   
                    LEFT JOIN #__wrd_transaction tr ON tr.transaction_id = e.transaction   
                	'

		. $where
		. $orderby;
        //echo $query; die;  
		return $query;
	}

	function _buildContentOrderBy(){
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');

		$filter_order     = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_author','filter_order','id' );
		$filter_order_Dir = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir',  'filter_order_Dir', 'DESC' );
		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir;
		return $orderby;
	}
    
	// Ham nay dung o dau? ai biet call Dinh gap...
	function delete($cid = array()){
		$result = false;

		if (count( $cid )){
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			//Update to summary Point
			$q = 'SELECT user_id,created_date FROM #__wrd_point WHERE id IN ( '.$cids.' )';
			$db = JFactory::getDbo();
			$db->setQuery($q);
			$rs = $db->loadObjectList();
			
			for($i=0;$i<count($rs);$i++){
				 
				$month = date('m',strtotime($rs[$i]->created_date));
				$year = date('Y',strtotime($rs[$i]->created_date));
				
				if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
					while(($month != date('m'))||($year != date('Y'))){
						WrdHelper::updateSummaryPoint($rs[$i]->user_id,$year,$month);
						if($month+1 <= 12) ++$month;
						else {$month = 1;++$year;}
					}
					WrdHelper::updateSummaryPoint($rs[$i]->user_id,date('Y'),date('m'));
				}
				
				$p_o_u = WrdHelper::getPoints($rs[$i]->user_id);
				$sql = 'UPDATE #__wrd_profile SET p_o_u = '.$p_o_u->point .' ,point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$rs[$i]->user_id;
				$db->setQuery($sql);
				$db->query();
			}
			
			$query = 'DELETE FROM #__wrd_point'
				. ' WHERE id IN ( '.$cids.' )';
			$this->_db->setQuery( $query );
			if(!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}
		return true;
	}
    
     //save to table $nametable
    function store($post,$tablename){
        $profile = JTable::getInstance($tablename, 'TableWrd');
        $profile->load();
        $profile->bind($post);
		$db = JFactory::getDbo();
		
		if ($profile->store()) {
			WrdHelper::updateSummaryPoint($post['user_id'],date('Y'),date('m'));
			WrdHelper::updatePointOfUser($post['user_id']);
			
			return $profile->id;
			
		} else {
			return 0;
		}
  	}
  	
  	function getList(){
  		$query = 'SELECT id AS value, name AS text FROM #__wrd_point WHERE published=1';

		$this->_db->setQuery( $query );
		return $this->_db->loadObjectList();
  	}

	function getUserList(){

		$query = 'SELECT a.created_id as value , b.username as text FROM #__wrd_point a LEFT JOIN #__users b ON a.created_id = b.id 
			GROUP BY a.created_id';
		
		$this->_db->setQuery( $query );
		return $this->_db->loadObjectList();
	}
  	
  	function getItem($id){
  		$query = 'SELECT * FROM #__wrd_point WHERE id = '.$id;
		$this->_db->setQuery($query);
		return $this->_db->loadObject();
  	}
  	
	function getPointOfUser($u_id){
		$db = JFactory::getDbo();
		$query = 'SELECT * FROM #__wrd_point WHERE user_id ='.$u_id;
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		return $rs;
	}
	function getPointOfTran($u_id, $tran_id){
		$db = JFactory::getDbo();
		$query = 'SELECT point FROM #__wrd_point WHERE `user_id` = '.$u_id.' and `transaction` = '.$tran_id ;
		
		$db->setQuery($query);
		
		$rs = $db->loadObject();
		return $rs;
		
	}
	function getRedemptionDetails($id){
		$db = JFactory::getDbo();
		$query = 'SELECT * FROM #__wrd_redemption WHERE id ='.$id;
		$db->setQuery($query);
		$rs = $db->loadObject();
		return $rs;
	}

	function UpdatePoint($id = 0, $point = 0, $modify = 0, $modify_date = ''){
		
		$db = JFactory::getDbo();
		$query = 'UPDATE #__wrd_point set `point` = '.$point.' , `modify_id` = '.$modify.', `modify_date` = "'.$modify_date.'" WHERE id ='.$id;
		$db->setQuery($query);
		$rs = $db->query();
		return $rs;
		
		/* update to summary_point*/
		$q = 'SELECT user_id,created_date FROM #__wrd_point WHERE id='.$id;
		$db->setQuery($q);
		$rows = $db->loadObjectList();
		if(count($rows)):
		foreach($rows as $row):
			$year = date("Y",strtotime($row->created_date));
			$month = date('m',strtotime($row->created_date));
			if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
				while(($month != date('m'))||($year != date('Y'))){
					WrdHelper::updateSummaryPoint($row->user_id,$year,$month);
					if($month+1 <= 12) ++$month;
					else {$month = 1;++$year;}
				}
				WrdHelper::updateSummaryPoint($row->user_id,date('Y'),date('m'));
			}//end if			
			
			$p_o_u = WrdHelper::getPoints($row->user_id);
			$sql = 'UPDATE #__wrd_profile SET p_o_u = '.$p_o_u->point .' ,point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$row->user_id;
			$db->setQuery($sql);
			$db->query();
			
		endforeach;endif;
	}
	
	function logPoint($id = 0,$rid = 0,$point = 0,$modify = 0){
		$db = JFactory::getDbo();
		$obj = new stdClass();
		$obj->id = null;
		$obj->pid = $id;
		$obj->rid = $rid;
		$obj->point = $point;
		$obj->created_id = $modify;
		$obj->created_date = date("Y-m-d H:i:s");
		
		$db->insertObject('#__wrd_lpointredemtion', $obj);
	}
	
	function DeletePoint($id = 0){
		$db = JFactory::getDbo();
		$q = 'SELECT user_id,created_date FROM #__wrd_point WHERE id='.$id;
		$db->setQuery($q);
		$rows = $db->loadObjectList();
		
		if(count($rows)): foreach($rows as $row):
			$year = date("Y",strtotime($row->created_date));
			$month = date('m',strtotime($row->created_date));
			if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
				while(($month != date('m'))||($year != date('Y'))){
					WrdHelper::updateSummaryPoint($row->user_id,$year,$month);
					if($month+1 <=12) ++$month;
					else {$month = 1;++$year;}
				}
				WrdHelper::updateSummaryPoint($row->user_id,date('Y'),date('m'));
				$p_o_u = WrdHelper::getPoints($row->user_id);
				$sql = 'UPDATE #__wrd_profile SET p_o_u = '.$p_o_u->point .' ,point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$row->user_id;
				$db->setQuery($sql);
				$db->query();
				
			}//end if
			
			
		endforeach;endif;
		
		$query = 'DELETE FROM #__wrd_point WHERE id ='.$id;
		$db->setQuery($query);
		$rs = $db->query();
		return $rs;
	}
	
	function ApproveRedemption($id = 0, $approve_date = '0000-00-00 00:00:00'){
		$db = JFactory::getDbo();
		$query = 'UPDATE #__wrd_redemption SET `approved` = 1 , `approved_date` = "'.$approve_date.'" , `point_id` = "" WHERE id ='.$id ;
		$db->setQuery($query);
		$rs = $db->query();
		return $rs;
	}
	
	function NoneApproveRedemption($id = 0, $approve_date = '0000-00-00 00:00:00'){
		$db = JFactory::getDbo();
		$query = 'UPDATE #__wrd_redemption SET `approved` = 2 , `approved_date` = "'.$approve_date.'" WHERE id ='.$id ;
		$db->setQuery($query);
		$rs = $db->query();
		return $rs;
	}
	
	function ReversePoint($user_id = 0, $point = 0, $created_id = 0){
		$db = JFactory::getDbo();
		$obj = new stdClass;
		$obj->id = null;
		$obj->user_id = $user_id;
		$obj->transaction = 0 ;
		$obj->type = '1';
		$obj->point = $point ;
		$obj->expire = '0000-00-00 00:00:00';
		$obj->point = $point ;
		$obj->des = 'Reverse point of customer';
		$obj->created_id = $created_id ;
		$obj->created_date = date('Y-m-d') ;
		$obj->modify_id = '';
		$obj->modify_date = '';
		$db->insertObject('#__wrd_point', $obj);
		
		WrdHelper::updateSummaryPoint($obj->user_id,date('Y'),date('m'));
		$p_o_u = WrdHelper::getPoints($obj->user_id);
		$sql = 'UPDATE #__wrd_profile SET p_o_u = '.$p_o_u->point .' ,point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$obj->user_id;
		$db->setQuery($sql);
		$db->query();
	}
	
	function ReverseProductQuantity($id = 0, $quantity = 1){
		$db = JFactory::getDbo();
		if($id != 0){
			$query = 'UPDATE #__wrd_products SET `quantity` = (`quantity` + '.intval($quantity).') WHERE id ='.$id ;
			$db->setQuery($query);
			$rs = $db->query();
		}
	}
}